package util

import (
	"dingusxp/trial/test/util/goroutine"
	"fmt"
	"runtime"
	"strings"
	"sync"
)

func FuncName() string {
	pc := make([]uintptr, 1)
	runtime.Callers(2, pc)
	f := runtime.FuncForPC(pc[0])
	return f.Name()
}

func True() bool {
	return true
}

var levels = make(map[uint64]int)
var mu sync.Mutex

// useage: defer Trace()() at the beginning of your func
func Trace() func() {

	var pc [32]uintptr
	n := runtime.Callers(2, pc[:])
	frames := runtime.CallersFrames(pc[:n])
	frame, _ := frames.Next()
	funcName := frame.Function

	gid := goroutine.GetID()
	mu.Lock()
	levels[gid]++
	mu.Unlock()

	indent := strings.Repeat("  ", levels[gid]-1)

	fmt.Printf("[g:%06d]%s -> %s\n", gid, indent, funcName)
	return func() {

		mu.Lock()
		levels[gid]--
		mu.Unlock()
		fmt.Printf("[g:%06d]%s <- %s\n", gid, indent, funcName)
	}
}
